# -*- coding: utf-8 -*-

# @Project : UI_DDTFrameWork
# @Author  : Mr.Deng
# @Time    : 2021/9/22 16:59

"""
发送邮件
"""

from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart

from common.tools.logConfig import Logger
from common.tools.decorator import error_collection
from common.tools.operateConfigData import OperateConfigData

from config.filePathConfig import *

import smtplib
import os

cf = OperateConfigData(projectConfigPath).read_config_data()


class SendEmail:

    def __init__(self):
        self.email = MIMEMultipart()
        self.Log = Logger().origin_logger

        # 邮件配置数据
        self.senderName = cf.get("email", "sender_name")
        self.senderAddress = cf.get("email", "sender_address")
        self.senderPwd = cf.get("email", "sender_password")
        self.receiverName = cf.get("email", "receiver_name")
        self.receiverAddress = cf.get("email", "receiver_address")
        self.subject = cf.get("email", "email_subject")
        self.text = cf.get("email", "email_text")

    def add_text_message(self):
        """
        添加邮件标题、正文内容信息
        :return:
        """
        # 发/收人的名称和邮箱地址
        self.email['From'] = formataddr((self.senderName, self.senderAddress))
        self.email['To'] = formataddr((self.receiverName, self.receiverAddress))
        # 添加文本信息
        self.email['Subject'] = self.subject
        text = MIMEText(self.text, "plain", "utf-8")
        self.email.attach(text)

    def add_new_report(self):
        """
        上传最新测试报告
        :return:
        """
        reportDirsLs = os.listdir(reportSavePath)
        # 把获取的报告文件列表文件按照创建顺序排列
        newReportList = sorted(reportDirsLs, key=lambda x: os.path.getctime(os.path.join(reportSavePath, x)))
        newReport = reportSavePath + newReportList[-1]
        att = MIMEText(open(newReport, 'rb').read(), 'base64', 'utf-8')
        att['content-Type'] = 'application/octet-stream'
        att['Content-Disposition'] = 'attachment; filename=autoTestReport.html'
        self.email.attach(att)

    @error_collection
    def send_email(self):
        """
        登录邮箱发送邮件
        :return:
        """
        try:
            # 服务器以及端口QQ邮箱端口是465，其他邮箱可以百度搜一下，服务和端口号
            server = smtplib.SMTP_SSL('smtp.qq.com', 465)
            self.add_text_message()
            self.add_new_report()
            # 登录邮箱，发送邮件
            server.login(self.senderAddress, self.senderPwd)
            server.sendmail(self.senderAddress, [self.receiverAddress], self.email.as_string())
            server.quit()
            self.Log.info(f"邮件已成功发送给：{self.receiverName}, {self.receiverAddress}")
        except:
            raise Exception("邮件发送失败！！！")

if __name__ == '__main__':
    SendEmail().send_email()
